const express = require("express");
const router = express.Router();

const Userinfo = require("../../models/UserInfo");

const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");

const passport = require("passport");

// @route   POST api/users/userregister
// @desc    注册 user
// @access  Public
router.post("/userregister", (req, res) => {
  // 查询数据库中是否拥有学号
  Userinfo.findOne({ number: req.body.number }).then((user) => {
    if (user) {
      return res.status(400).json("学号已被注册!");
    } else {
      const newUser = new Userinfo({
        name: req.body.name,
        number: req.body.number,
        password: req.body.password,
      });

      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;

          newUser.password = hash;

          newUser
            .save()
            .then((user) => res.json(user))
            .catch((err) => console.log(err));
        });
      });
    }
  });
});

// @route   post api/users/userlogin
// @desc    登录 user
// @access  Public
router.post("/userlogin", (req, res) => {
  const number = req.body.number;
  const password = req.body.password;

  Userinfo.findOne({ number }).then((user) => {
    if (!user) {
      return res.status(404).json("用户不存在!");
    }

    // 密码匹配
    bcrypt.compare(password, user.password).then((isMatch) => {
      if (isMatch) {
        const rule = {
          id: user.id,
          name: user.name,
          // number: user.number, /////////////////////
          number: user.number,
          score: user.score,
          rank: user.rank,
          role: user.role,
        };
        jwt.sign(rule, keys.secretOrKey, { expiresIn: 36000 }, (err, token) => {
          if (err) throw err;
          res.json({
            success: true,
            token: "Bearer " + token,
          });
        });
        // res.json({msg:"success"});
      } else {
        return res.status(400).json("密码错误!");
      }
    });
  });
});

// @route   get api/users/getinfo/:id
// @desc    获取 单个user 信息
// @access  Private
router.get(
  "/getinfo/:id",
  //passport.authenticate("jwt", { session: false }),
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Userinfo.findOne({ _id: req.params.id })
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route   post api/users/editinfo/:id
// @desc    修改 user 信息
// @access  Private
router.post(
  "/editinfo/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const infoFields = {};

    if (req.body.number) infoFields.number = req.body.number;
    if (req.body.name) infoFields.name = req.body.name;

    if (req.body.score) infoFields.score = req.body.score;
    if (req.body.rank) infoFields.rank = req.body.rank;

    Userinfo.findOneAndUpdate(
      { _id: req.params.id },
      { $set: infoFields },
      { new: true }
    ).then((info) => res.json(info));
  }
);

// @route   get api/users/getuserinfo
// @desc    获取所有 user 信息
// @access  Private
router.get(
  "/getuserinfo",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Userinfo.find()
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }
        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route   post api/users/edituserinfo/:id
// @desc    管理员修改 user 信息，包括学号、姓名、角色
// @access  Private
router.post(
  "/edituserinfo/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const infoFields = {};

    if (req.body.number) infoFields.number = req.body.number;
    if (req.body.name) infoFields.name = req.body.name;
    if (req.body.role) infoFields.role = req.body.role;

    Userinfo.findOneAndUpdate(
      { _id: req.params.id },
      { $set: infoFields },
      { new: true }
    ).then((info) => res.json(info));
  }
);

// @route  POST api/users/updateusers
// @desc   将多个数据更新进用户信息表
// @access Private
router.post(
  "/updateusers",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // 检查 req.body 是否为数组
    if (!Array.isArray(req.body)) {
      return res.status(400).json("请求数据不是数组!");
    }

    // 遍历数组，更新用户信息
    req.body.forEach((user) => {
      Userinfo.findOneAndUpdate(
        { _id: user._id },
        { $set: user },
        { new: true }
      ).then((info) => {
        //console.log(info);
      });
    });

    res.json("更新成功!");
  }
);

// @route   delete api/users/deleteuser/:id
// @desc    管理员删除 user 信息
// @access  Private
router.delete(
  "/deleteuser/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Userinfo.findByIdAndDelete(req.params.id)
      .then((profile) => {
        res.json(profile);
      })
      .catch((err) => res.status(404).json("删除失败!"));
  }
);

// router.delete(
//   "/deleteuser/:id",
//   passport.authenticate("jwt", { session: false }),
//   (req, res) => {
//     Userinfo.findByIdAndDelete(req.params.id)
//       .then((profile) => {
//         profile.save().then((profile) => res.json(profile));
//       })
//       .catch((err) => res.status(404).json("删除失败!"));
//   }
// );

module.exports = router;
